package com.yupi.shortchain.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.shortchain.common.ErrorCode;
import com.yupi.shortchain.constant.UserConstant;
import com.yupi.shortchain.exception.BusinessException;
import com.yupi.shortchain.model.entity.User;
import com.yupi.shortchain.model.enums.UserRoleEnum;
import com.yupi.shortchain.model.vo.LoginUserVO;
import com.yupi.shortchain.model.vo.TokenLoginUserVO;
import com.yupi.shortchain.service.UserService;
import com.yupi.shortchain.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;

/**
* @author liu
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2024-12-03 10:12:15
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    @Resource
    private UserMapper userMapper;
    /**
     * 盐值，混淆密码
     */
    public static final String SALT = "yupi";

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        // 密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }
        synchronized (userAccount.intern()) {
            // 账户不能重复
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("userAccount", userAccount);
            long count = this.baseMapper.selectCount(queryWrapper);
            if (count > 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
            }
            // 2. 加密
            String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
            // 3. 插入数据
            User user = new User();
            user.setUserAccount(userAccount);
            user.setUserPassword(encryptPassword);
            boolean saveResult = this.save(user);
            if (!saveResult) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
            }
            return user.getId();
        }
    }

    @Override
    public LoginUserVO userLogin(String userAccount, String userPassword) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号错误");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = this.baseMapper.selectOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        // 3. 记录用户的登录态
        log.info("=========================================");
        log.info("user login success {}",user.getId());
        StpUtil.login(user.getId());

        StpUtil.getTokenSession().set(UserConstant.USER_LOGIN_STATE, user);
        return this.getTokenLoginUserVO(user);
    }

    @Override
    public LoginUserVO getLoginUserVO() {
        int loginId = StpUtil.getLoginIdAsInt();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", loginId);
        User user = userMapper.selectOne(queryWrapper);
        log.info("create Time {}",user.getCreateTime());
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtils.copyProperties(user, loginUserVO);
        log.info("当前用户");
        return loginUserVO;
    }

    @Override
    public User getLoginUser() {
        if(!StpUtil.isLogin()){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        //从token中得到的用户信息 可能与数据库中的信息不一致 所以从数据库中查询准确信息
        User user = (User)StpUtil.getTokenSession().get(UserConstant.USER_LOGIN_STATE);
        User currentUser = userMapper.selectById(user.getId());
        if(currentUser == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentUser;
    }

    @Override
    public boolean isAdmin() {
        User  user = (User) StpUtil.getTokenSession().get(UserConstant.USER_LOGIN_STATE);
        return isAdmin(user);
    }

    @Override
    public boolean isAdmin(User user) {
        return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }


    /**
     * 获取 TokenLoginUserVO
     * @param user
     * @return
     */
    public TokenLoginUserVO getTokenLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        TokenLoginUserVO loginUserVO = new TokenLoginUserVO();
        BeanUtils.copyProperties(user, loginUserVO);
        //获取 Token  相关参数
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        loginUserVO.setSaTokenInfo(tokenInfo);
        return loginUserVO;
    }

}




